package express.compiler;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class Tokenizer {
    private String exprString;
    private String currToken = "";
    private List<String> tokens = Lists.newArrayList();

    public Tokenizer(String exprString) {
        this.exprString = exprString;
    }

    public String getAndRemoveKeyword(String keyword) {
        if(StringUtils.startsWithIgnoreCase(exprString, keyword)) {
            exprString = StringUtils.removeStartIgnoreCase(exprString, keyword);
            return keyword;
        } else {
            return null;
        }
    }

    public List<String> tokenizer() {
       String[] specKeywords = new String[]{"&&","||","&","|","+","-","*","/"};

        while (StringUtils.isNotBlank(this.exprString)) {
            for (String specKeyword : specKeywords) {
                String keyword = getAndRemoveKeyword(specKeyword);
                if(keyword != null) {
                    if(StringUtils.isNotEmpty(this.currToken)) {
                        tokens.add(this.currToken);
                        this.currToken = "";
                    }
                    tokens.add(keyword);
                    break;
                }
            }

            String one = StringUtils.substring(exprString, 0, 1);
            exprString = StringUtils.substring(exprString, 1);

            //丢弃逗号
            if(StringUtils.equals(one,",")) {
                if(StringUtils.isNotEmpty(currToken)) {
                    this.tokens.add(currToken);
                    this.currToken = "";
                }
                continue;
            }

            if(StringUtils.equalsAny(one,"(",")")) {
                if(StringUtils.isNotEmpty(currToken)) {
                    this.tokens.add(currToken);
                    this.currToken = "";
                }
                this.tokens.add(one);
                continue;
            }

            if(StringUtils.equalsAny(one,Keywords.PARAM_START, Keywords.PARAM_END)) {
                if(StringUtils.isNotEmpty(currToken)) {
                    this.tokens.add(currToken);
                    this.currToken = "";
                }
                this.tokens.add(one);
                continue;
            }

            if(StringUtils.equalsAny(one, " ","\n","\r")) {
                if(StringUtils.isNotEmpty(currToken)) {
                    this.tokens.add(currToken);
                    this.currToken = "";
                }
                continue;
            }

            this.currToken += one;
        }

        if(StringUtils.isNotBlank(this.currToken)) {
            this.tokens.add(this.currToken);
        }

        return this.tokens;
    }
}
